package com.geekcoding.geekoj.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.geekcoding.common.dto.ApiResponse;
import com.geekcoding.geekoj.constant.CommonConstants;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.nums.WebContextKey;
import com.geekcoding.geekoj.repository.UserEntityRepository;
import com.geekcoding.geekoj.utils.JWTUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;

@Component
@RequiredArgsConstructor
public class WebHandleInterceptor implements HandlerInterceptor {

    private final UserEntityRepository userEntityRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        val userToken = request.getHeader(CommonConstants.TOKEN);
        String userId = null;
        if (StrUtil.isNotBlank(userToken)) {
            userId = JWTUtils.getUserId(userToken);
        }
        UserEntity currentUser = null;
        if (StrUtil.isNotBlank(userId)) {
            currentUser = userEntityRepository.getById(userId);
        }
        if (Objects.isNull(currentUser)) {
            returnNoLogin(response);
            return false;
        }
        WebContextHolder.set(WebContextKey.CURRENT_USER, currentUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WebContextHolder.remove();
    }

    private void returnNoLogin(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setStatus(401);
        response.setContentType("Application/json;charset=utf-8");
        ApiResponse apiResponse = ApiResponse.serviceError(401, "请先登录");
        outputStream.write(JSONUtil.toJsonStr(apiResponse).getBytes(Charset.defaultCharset()));
    }
}
